package com.aim.config.shiro;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @AUTO 用户权限拦截器
 * @Author AIM
 * @DATE 2019/4/24
 */
public class ShiroUserFilter extends AccessControlFilter {

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o) throws Exception {
		if (isLoginRequest(request, response)) {
			return true;
		} else {
			Subject subject = getSubject(request, response);
			// If principal is not null, then the user is known and should be allowed access.
			return subject.getPrincipal() != null;
		}
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
		HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
		String requestHeader = httpServletRequest.getHeader("x-requested-with");
		/**
		 * 如果是ajax请求则不进行跳转
		 */
		if (requestHeader != null && requestHeader.equalsIgnoreCase("XMLHttpRequest")) {
			httpServletResponse.setHeader("sessionstatus", "timeout");
			httpServletResponse.sendError(httpServletResponse.SC_UNAUTHORIZED, "登录超时");
			return false;
		} else {
			/**
			 * 第一次点击页面
			 */
			String referer = httpServletRequest.getHeader("Referer");
			if (referer == null) {
				saveRequestAndRedirectToLogin(request, response);
				return false;
			} else {
				/**
				 * 从别的页面跳转过来的
				 */
				if (ShiroKit.getSession().getAttribute("sessionFlag") == null) {
					httpServletRequest.setAttribute("tips", "session超时");
					httpServletRequest.getRequestDispatcher("/login").forward(request, response);
					return false;
				} else {
					saveRequestAndRedirectToLogin(request, response);
					return false;
				}
			}
		}
	}
}
